from PySide6.QtGui import QResizeEvent
from qfluentwidgets import InfoBar, StateToolTip

from tools import FileInformation
from view.base import TableFrameBase
from components import OpenFileDialog

from common import SheepToExcelThread
from ..base import ReturnView


class SheetToExcelView(ReturnView):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.stateToolTip = StateToolTip('Sheet To Excel', '正在根据Sheet页拆分Excel，请稍后...', self)
        self.stateToolTip.hide()

        self.table = TableFrameBase()
        self.table.setTitle('Sheet To Excel')
        self.table.setHeaders(['名称', '完整路径', '创建日期', '类型', '大小'])

        self.to_pdf_thread = SheepToExcelThread(self)

        self.returnButton.clicked.connect(self.returned_event)
        self.table.added.connect(self.add_file_event)
        self.table.saved.connect(self.save_event)
        self.table.started.connect(self.started_event)
        self.to_pdf_thread.started.connect(self.started_thread)
        self.to_pdf_thread.error.connect(lambda msg: InfoBar.error('错误', msg, duration=5000, parent=self))
        self.to_pdf_thread.finished.connect(self.finished_event)

        self.vBox.addWidget(self.table)

    def add_file_event(self):
        files = OpenFileDialog(self).getOpenFileNames(filter='Excel文件(*.xls;*.xlsx)')[0]
        for file in files:
            if file in self.table.getColumnValues(1):
                InfoBar.warning('提示', file + ' 已存在', duration=2000, parent=self)
                continue
            fp = FileInformation(file)
            self.table.addItem([fp.name(), file, fp.st_ctime(), fp.suffix(), fp.size()])

    def save_event(self):
        file = OpenFileDialog(self).getExistingDirectory()
        self.table.setLineText(file)

    def started_thread(self):
        self.stateToolTip.show()

    def finished_event(self):
        self.stateToolTip.hide()
        InfoBar.success('成功', '转换成功', duration=3000, parent=self)

    def started_event(self):
        excel_list = self.table.getColumnValues(1)
        save_path = self.table.lineText()
        self.to_pdf_thread.set_value(excel_list, save_path)
        self.to_pdf_thread.start()

    def resizeEvent(self, event: QResizeEvent):
        self.stateToolTip.move(event.size().width() - self.stateToolTip.width() - 20, 10)
        super().resizeEvent(event)

    def returned_event(self):
        self.table.clear()
        self.returned.emit()
